package com.tpay.server.service;

import java.util.Calendar;
import java.util.Set;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.google.inject.Inject;
import com.tpay.server.GeneralDao;
import com.tpay.server.domain.Cgroup;
import com.tpay.server.domain.CgroupApp;
import com.tpay.server.domain.User;
import com.tpay.shared.action.LoginAction;
import com.tpay.shared.action.LoginResult;
import com.tpay.shared.exception.MyException;

public class LoginService {
	private static Logger logger = LoggerFactory.getLogger(LoginService.class);
	
	@Inject GeneralDao dao;
	
	public LoginResult login(LoginAction action, HttpServletRequest req) {
		User user;
		
		try {
			user = dao.getEm().createQuery("from User t where t.email = ?", User.class)
							.setParameter(1, action.getEmail())
							.getSingleResult();
		} catch (Exception e) {
			throw new MyException(action.getEmail() + "는 존재하지 않는 사용자입니다.", "LOGIN-001");
		}
		
		if(!user.getPassword().equals(action.getPassword()))
			throw new MyException("패스워드가 일치하지 않습니다.", "LOGIN-002");
	
		Cgroup cgroup = user.getCgroup();	// 소속회사그룹
		
		Calendar cal = Calendar.getInstance();	// 현재 날짜
		if(cal.after(cgroup.getEndDate()))
			throw new MyException(cgroup.getName() + "의 시스템 사용기간이 만료되었습니다.", "LOGIN-003");
		
		boolean foundApp = false;
		Set<CgroupApp> cgroupApps = cgroup.getCgroupApps();
		
		for(CgroupApp item : cgroupApps) {
			if(item.getApp().getId().equals("HR")) {
				foundApp = true;
				break;
			}
		}
		
		if(foundApp == false)
			throw new MyException(cgroup.getName() + " : 급여 모듈을 사용할 수 있게 등록되어 있지 않습니다.", "LOGIN-004");
		
		// sessionKey
		HttpSession session = null;
		
		if(req != null) {
			session = req.getSession();
			session.setAttribute("login.authenticated", action.getEmail());
		}
		
		return new LoginResult(session.getId());
	}
}
